<template>
  <section 
    id="header-search" 
    :class="`pt-24 pb-12 transition-all duration-300 ${hasBackground ? 'bg-light' : ''}`"
    :style="getBackgroundStyles()"
  >
    <div class="container mx-auto px-4 sm:px-6 lg:px-8">
      <div class="flex flex-col md:flex-row items-center justify-between">
        <!-- 标题区域 -->
        <div class="mb-6 md:mb-0" :class="titleAlignment">
          <h1 
            class="text-2xl md:text-3xl font-bold transition-all duration-300"
            :style="{ color: titleColor }"
          >
            {{ title }}
          </h1>
          <p 
            class="text-gray-600 transition-all duration-300"
            :style="{ color: subtitleColor }"
          >
            {{ subtitle }}
          </p>
        </div>
        
        <!-- 搜索区域 -->
        <div class="w-full md:w-auto relative w-full max-w-xl">
          <div class="relative">
            <input 
              type="text" 
              :placeholder="placeholderText" 
              v-model="searchQuery"
              class="w-full pl-10 pr-10 py-3 rounded-lg border transition-all duration-300 focus:outline-none focus:ring-2"
              :class="getInputClasses()"
              @input="handleInput"
              @keydown.enter="handleSearch"
              @focus="handleFocus"
              @blur="handleBlur"
            >
            
            <!-- 搜索图标 -->
            <i 
              class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 transition-all duration-300"
              :style="{ color: isFocused ? primaryColor : 'rgba(31, 41, 55, 0.5)' }"
            ></i>
            
            <!-- 清除按钮 -->
            <button 
              v-if="searchQuery && showClearButton"
              class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-800 transition-all duration-300"
              @click="clearSearch"
              aria-label="清除搜索内容"
            >
              <i class="fa fa-times"></i>
            </button>
            
            <!-- 搜索按钮 -->
            <button 
              v-if="showSearchButton"
              class="absolute right-3 top-1/2 -translate-y-1/2 px-3 py-1 rounded text-sm transition-colors"
              :style="{ 
                backgroundColor: `${primaryColor}10`,
                color: primaryColor
              }"
              @click="handleSearch"
            >
              搜索
            </button>
          </div>
          
          <!-- 搜索建议 -->
          <div 
            v-if="showSuggestions && suggestions.length > 0 && isFocused"
            class="absolute left-0 right-0 top-full mt-1 bg-white border rounded-lg shadow-lg z-10 max-h-60 overflow-y-auto"
          >
            <div 
              v-for="(suggestion, index) in suggestions" 
              :key="index"
              class="px-4 py-2 hover:bg-gray-50 cursor-pointer transition-all duration-300 flex items-center"
              @click="selectSuggestion(suggestion)"
            >
              <i class="fa fa-search text-primary/50 mr-2"></i>
              <span v-html="highlightMatch(suggestion)"></span>
            </div>
          </div>
          
          <!-- 热门搜索标签 -->
          <div 
            v-if="showTrendingTags && trendingTags.length > 0 && !searchQuery && !isFocused"
            class="mt-3 flex flex-wrap gap-2"
          >
            <span class="text-sm text-gray-600">热门搜索:</span>
            <a 
              v-for="(tag, index) in trendingTags" 
              :key="index"
              class="text-sm px-3 py-1 bg-gray-100 hover:bg-gray-200 rounded-full transition-all duration-300 cursor-pointer"
              @click="handleTagClick(tag)"
            >
              {{ tag }}
            </a>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>

<script>
export default {
  name: 'SearchSection',
  // 低代码平台元数据
  lowcode: {
    meta: {
      name: 'search-section',
      displayName: '搜索模块',
      description: '网站资源中心的搜索功能模块，支持搜索建议和热门标签',
      icon: 'fa-search',
      category: '交互组件',
      version: '1.0.0',
      isContainer: false
    },
    
    configPanel: [
      {
        title: '基本配置',
        fields: [
          {
            name: 'primaryColor',
            label: '主题色',
            type: 'color',
            defaultValue: '#165DFF'
          },
          {
            name: 'title',
            label: '标题',
            type: 'text',
            defaultValue: '智联科技资源中心'
          },
          {
            name: 'subtitle',
            label: '副标题',
            type: 'text',
            defaultValue: '查找您需要的产品、文章和解决方案'
          },
          {
            name: 'placeholderText',
            label: '搜索框提示文字',
            type: 'text',
            defaultValue: '搜索产品、文章或解决方案...'
          }
        ]
      },
      {
        title: '样式配置',
        fields: [
          {
            name: 'hasBackground',
            label: '显示背景',
            type: 'boolean',
            defaultValue: true
          },
          {
            name: 'bgColor',
            label: '背景色',
            type: 'color',
            defaultValue: '#f9fafb'
          },
          {
            name: 'titleColor',
            label: '标题颜色',
            type: 'color',
            defaultValue: '#1f2937'
          },
          {
            name: 'subtitleColor',
            label: '副标题颜色',
            type: 'color',
            defaultValue: 'rgba(31, 41, 55, 0.7)'
          },
          {
            name: 'titleAlignment',
            label: '标题对齐方式',
            type: 'select',
            options: [
              { label: '左对齐', value: 'text-left' },
              { label: '居中对齐', value: 'text-center' },
              { label: '右对齐', value: 'text-right' }
            ],
            defaultValue: 'text-left'
          },
          {
            name: 'inputSize',
            label: '输入框大小',
            type: 'select',
            options: [
              { label: '小', value: 'small' },
              { label: '中', value: 'medium' },
              { label: '大', value: 'large' }
            ],
            defaultValue: 'medium'
          }
        ]
      },
      {
        title: '功能配置',
        fields: [
          {
            name: 'showClearButton',
            label: '显示清除按钮',
            type: 'boolean',
            defaultValue: true
          },
          {
            name: 'showSearchButton',
            label: '显示搜索按钮',
            type: 'boolean',
            defaultValue: false
          },
          {
            name: 'showSuggestions',
            label: '显示搜索建议',
            type: 'boolean',
            defaultValue: true
          },
          {
            name: 'showTrendingTags',
            label: '显示热门标签',
            type: 'boolean',
            defaultValue: true
          },
          {
            name: 'debounceTime',
            label: '输入防抖时间(ms)',
            type: 'number',
            min: 100,
            max: 1000,
            defaultValue: 300
          }
        ]
      },
      {
        title: '数据配置',
        fields: [
          {
            name: 'trendingTags',
            label: '热门搜索标签',
            type: 'array',
            defaultValue: [
              '数字化转型',
              '人工智能',
              '云计算',
              '大数据分析',
              '企业解决方案'
            ]
          },
          {
            name: 'suggestionsSource',
            label: '搜索建议来源',
            type: 'select',
            options: [
              { label: '本地静态数据', value: 'local' },
              { label: '远程API', value: 'remote' }
            ],
            defaultValue: 'local'
          },
          {
            name: 'localSuggestions',
            label: '本地搜索建议数据',
            type: 'array',
            defaultValue: [
              '数字化转型解决方案',
              '人工智能在企业中的应用',
              '云计算服务平台',
              '大数据分析工具',
              '企业资源规划系统',
              '智能制造解决方案',
              '物联网平台搭建',
              '企业安全防护系统'
            ]
          },
          {
            name: 'remoteSuggestionsUrl',
            label: '远程建议API地址',
            type: 'text',
            defaultValue: '/api/search/suggestions'
          }
        ]
      }
    ],
    
    events: [
      {
        name: 'search',
        label: '搜索事件',
        description: '当执行搜索时触发',
        parameters: [
          { name: 'query', type: 'string', description: '搜索关键词' },
          { name: 'timestamp', type: 'number', description: '搜索时间戳' }
        ]
      },
      {
        name: 'suggestionSelect',
        label: '选择搜索建议',
        description: '当用户选择一个搜索建议时触发',
        parameters: [
          { name: 'suggestion', type: 'string', description: '选中的建议文本' }
        ]
      },
      {
        name: 'tagClick',
        label: '热门标签点击',
        description: '当用户点击热门标签时触发',
        parameters: [
          { name: 'tag', type: 'string', description: '点击的标签文本' }
        ]
      },
      {
        name: 'inputChange',
        label: '输入变化',
        description: '当搜索输入框内容变化时触发',
        parameters: [
          { name: 'value', type: 'string', description: '输入框当前值' }
        ]
      }
    ],
    
    actions: [
      {
        name: 'setSearchQuery',
        label: '设置搜索关键词',
        description: '手动设置搜索框中的关键词',
        parameters: [
          { name: 'query', type: 'string', required: true, description: '搜索关键词' }
        ]
      },
      {
        name: 'clearSearch',
        label: '清除搜索',
        description: '清空搜索框内容'
      },
      {
        name: 'doSearch',
        label: '执行搜索',
        description: '触发搜索操作，使用当前搜索框中的内容'
      },
      {
        name: 'updateTrendingTags',
        label: '更新热门标签',
        description: '动态更新热门搜索标签',
        parameters: [
          { name: 'tags', type: 'array', required: true, description: '标签数组' }
        ]
      }
    ]
  },
  
  props: {
    // 基本配置
    primaryColor: {
      type: String,
      default: '#165DFF'
    },
    title: {
      type: String,
      default: '智联科技资源中心'
    },
    subtitle: {
      type: String,
      default: '查找您需要的产品、文章和解决方案'
    },
    placeholderText: {
      type: String,
      default: '搜索产品、文章或解决方案...'
    },
    children: {
      type: Array,
      default: () => []
    },
    // 样式配置
    hasBackground: {
      type: Boolean,
      default: true
    },
    bgColor: {
      type: String,
      default: '#f9fafb'
    },
    titleColor: {
      type: String,
      default: '#1f2937'
    },
    subtitleColor: {
      type: String,
      default: 'rgba(31, 41, 55, 0.7)'
    },
    titleAlignment: {
      type: String,
      default: 'text-left',
      validator: (value) => ['text-left', 'text-center', 'text-right'].includes(value)
    },
    inputSize: {
      type: String,
      default: 'medium',
      validator: (value) => ['small', 'medium', 'large'].includes(value)
    },
    
    // 功能配置
    showClearButton: {
      type: Boolean,
      default: true
    },
    showSearchButton: {
      type: Boolean,
      default: false
    },
    showSuggestions: {
      type: Boolean,
      default: true
    },
    showTrendingTags: {
      type: Boolean,
      default: true
    },
    debounceTime: {
      type: Number,
      default: 300,
      validator: (value) => value >= 100 && value <= 1000
    },
    
    // 数据配置
    trendingTags: {
      type: Array,
      default: () => [
        '数字化转型',
        '人工智能',
        '云计算',
        '大数据分析',
        '企业解决方案'
      ]
    },
    suggestionsSource: {
      type: String,
      default: 'local',
      validator: (value) => ['local', 'remote'].includes(value)
    },
    localSuggestions: {
      type: Array,
      default: () => [
        '数字化转型解决方案',
        '人工智能在企业中的应用',
        '云计算服务平台',
        '大数据分析工具',
        '企业资源规划系统',
        '智能制造解决方案',
        '物联网平台搭建',
        '企业安全防护系统'
      ]
    },
    remoteSuggestionsUrl: {
      type: String,
      default: '/api/search/suggestions'
    }
  },
  
  data() {
    return {
      searchQuery: '',
      suggestions: [],
      isFocused: false,
      debounceTimer: null
    };
  },
  
  methods: {
    /**
     * 获取背景样式
     */
    getBackgroundStyles() {
      if (this.hasBackground) {
        return {
          backgroundColor: this.bgColor
        };
      }
      return {};
    },
    
    /**
     * 获取输入框样式类
     */
    getInputClasses() {
      // 基础样式
      const classes = [
        'border-gray-300',
        'focus:ring-primary/50',
        `focus:border-${this.primaryColor.replace('#', '')}`
      ];
      
      // 根据输入框大小调整样式
      switch (this.inputSize) {
        case 'small':
          classes.push('px-8', 'py-2', 'text-sm');
          break;
        case 'large':
          classes.push('px-10', 'py-4', 'text-lg');
          break;
        default: // medium
          classes.push('px-10', 'py-3');
      }
      
      return classes.join(' ');
    },
    
    /**
     * 处理输入事件（带防抖）
     */
    handleInput() {
      // 触发输入变化事件
      this.$emit('inputChange', {
        value: this.searchQuery
      });
      
      // 如果关闭了搜索建议，直接返回
      if (!this.showSuggestions) {
        return;
      }
      
      // 清除之前的定时器
      if (this.debounceTimer) {
        clearTimeout(this.debounceTimer);
      }
      
      // 如果搜索词为空，清空建议
      if (!this.searchQuery.trim()) {
        this.suggestions = [];
        return;
      }
      
      // 设置新的定时器
      this.debounceTimer = setTimeout(() => {
        this.fetchSuggestions();
      }, this.debounceTime);
    },
    
    /**
     * 获取搜索建议
     */
    fetchSuggestions() {
      if (this.suggestionsSource === 'local') {
        // 本地建议
        const query = this.searchQuery.toLowerCase().trim();
        this.suggestions = this.localSuggestions
          .filter(item => item.toLowerCase().includes(query))
          .slice(0, 8); // 限制最多显示8条建议
      } else {
        // 远程API获取建议
        // 实际项目中应该使用axios等库发送请求
        fetch(`${this.remoteSuggestionsUrl}?q=${encodeURIComponent(this.searchQuery)}`)
          .then(response => response.json())
          .then(data => {
            if (Array.isArray(data.suggestions)) {
              this.suggestions = data.suggestions.slice(0, 8);
            }
          })
          .catch(error => {
            console.error('Failed to fetch suggestions:', error);
            this.$emit('error', {
              type: 'suggestions',
              message: '获取搜索建议失败',
              error
            });
          });
      }
    },
    
    /**
     * 处理搜索
     */
    handleSearch() {
      if (this.searchQuery.trim()) {
        this.$emit('search', {
          query: this.searchQuery.trim(),
          timestamp: new Date().getTime()
        });
        
        // 搜索后关闭建议面板
        this.suggestions = [];
      }
    },
    
    /**
     * 清除搜索内容
     */
    clearSearch() {
      this.searchQuery = '';
      this.suggestions = [];
      this.$emit('inputChange', {
        value: ''
      });
    },
    
    /**
     * 选择搜索建议
     */
    selectSuggestion(suggestion) {
      this.searchQuery = suggestion;
      this.$emit('suggestionSelect', {
        suggestion
      });
      this.handleSearch();
    },
    
    /**
     * 处理热门标签点击
     */
    handleTagClick(tag) {
      this.searchQuery = tag;
      this.$emit('tagClick', {
        tag
      });
      this.handleSearch();
    },
    
    /**
     * 处理输入框获得焦点
     */
    handleFocus() {
      this.isFocused = true;
      // 如果有搜索内容，显示建议
      if (this.searchQuery.trim() && this.showSuggestions) {
        this.fetchSuggestions();
      }
    },
    
    /**
     * 处理输入框失去焦点
     */
    handleBlur() {
      // 延迟关闭，以便点击建议
      setTimeout(() => {
        this.isFocused = false;
      }, 200);
    },
    
    /**
     * 高亮匹配的文本
     */
    highlightMatch(text) {
      if (!this.searchQuery) return text;
      const regex = new RegExp(`(${this.searchQuery})`, 'gi');
      return text.replace(regex, '<span style="color: ' + this.primaryColor + '; font-weight: 500">$1</span>');
    },
    
    /**
     * 手动设置搜索关键词
     */
    setSearchQuery(query) {
      this.searchQuery = query;
      this.$emit('inputChange', {
        value: query
      });
    },
    
    /**
     * 执行搜索（外部调用）
     */
    doSearch() {
      this.handleSearch();
    },
    
    /**
     * 更新热门标签
     */
    updateTrendingTags(tags) {
      if (Array.isArray(tags)) {
        this.trendingTags = tags;
      }
    }
  }
};
</script>

<style scoped>
/* 已替换为Tailwind CSS样式 */
</style>
    